import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../controllers/main_tab_controller.dart';

class TabPage extends StatelessWidget {
  const TabPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(MainTabController());
    
    return WillPopScope(
      onWillPop: controller.onWillPop,
      child: GetBuilder<MainTabController>(
        builder: (controller) {
          return Scaffold(
            appBar: AppBar(
              title: Text(controller.getCurrentTitle()),
              automaticallyImplyLeading: false,
              actions: [
                // 角标测试按钮
                IconButton(
                  icon: const Icon(Icons.notifications),
                  onPressed: () => _showBadgeTestDialog(context, controller),
                ),
                // 更多操作
                PopupMenuButton<String>(
                  onSelected: (value) {
                    switch (value) {
                      case 'clear_badges':
                        controller.clearAllBadges();
                        Get.snackbar('提示', '已清除所有角标');
                        break;
                      case 'test_navigation':
                        _showNavigationTestDialog(context, controller);
                        break;
                    }
                  },
                  itemBuilder: (context) => [
                    const PopupMenuItem(
                      value: 'clear_badges',
                      child: Row(
                        children: [
                          Icon(Icons.clear_all),
                          SizedBox(width: 8),
                          Text('清除角标'),
                        ],
                      ),
                    ),
                    const PopupMenuItem(
                      value: 'test_navigation',
                      child: Row(
                        children: [
                          Icon(Icons.navigation),
                          SizedBox(width: 8),
                          Text('导航测试'),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
            body: SafeArea(
              child: IndexedStack(
                index: controller.currentIndex,
                children: [
                  _buildTabContent(0, '首页', Icons.home, Colors.blue),
                  _buildTabContent(1, '列表', Icons.list, Colors.green),
                  _buildTabContent(2, '我的', Icons.person, Colors.orange),
                  _buildTabContent(3, '设置', Icons.settings, Colors.purple),
                ],
              ),
            ),
            bottomNavigationBar: BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              currentIndex: controller.currentIndex,
              onTap: controller.changeTab,
              items: _buildBottomNavItems(controller),
              selectedItemColor: Theme.of(context).colorScheme.primary,
              unselectedItemColor: Colors.grey,
              selectedFontSize: 12.sp,
              unselectedFontSize: 12.sp,
            ),
          );
        },
      ),
    );
  }

  Widget _buildTabContent(int index, String title, IconData icon, Color color) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 64.w, color: color),
          SizedBox(height: 16.h),
          Text(
            title,
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '这是$title页面的内容',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 24.h),
          ElevatedButton(
            onPressed: () {
              Get.snackbar('提示', '您点击了$title页面的按钮');
            },
            child: Text('$title功能'),
          ),
        ],
      ),
    );
  }

  List<BottomNavigationBarItem> _buildBottomNavItems(MainTabController controller) {
    return controller.tabs.asMap().entries.map((entry) {
      final index = entry.key;
      final tab = entry.value;
      final badgeCount = controller.badgeCounts[index] ?? 0;
      
      // 添加角标
      if (badgeCount > 0) {
        Widget badgeWidget = Badge(
          label: Text(
            badgeCount > 99 ? '99+' : badgeCount.toString(),
            style: TextStyle(
              fontSize: 10.sp,
              color: Colors.white,
            ),
          ),
          backgroundColor: Colors.red,
          child: tab.icon,
        );
        
        return BottomNavigationBarItem(
          icon: badgeWidget,
          label: tab.label,
        );
      }
      
      return BottomNavigationBarItem(
        icon: tab.icon!,
        label: tab.label,
      );
    }).toList();
  }

  void _showBadgeTestDialog(BuildContext context, MainTabController controller) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('角标测试'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('为不同Tab添加角标数字：'),
            SizedBox(height: 16.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                    controller.setBadgeCount(0, 5);
                    Navigator.pop(context);
                  },
                  child: const Text('首页+5'),
                ),
                ElevatedButton(
                  onPressed: () {
                    controller.setBadgeCount(1, 12);
                    Navigator.pop(context);
                  },
                  child: const Text('列表+12'),
                ),
              ],
            ),
            SizedBox(height: 8.h),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                    controller.setBadgeCount(2, 99);
                    Navigator.pop(context);
                  },
                  child: const Text('我的+99'),
                ),
                ElevatedButton(
                  onPressed: () {
                    controller.setBadgeCount(3, 999);
                    Navigator.pop(context);
                  },
                  child: const Text('设置+999'),
                ),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _showNavigationTestDialog(BuildContext context, MainTabController controller) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('导航测试'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('选择要跳转的Tab：'),
            SizedBox(height: 16.h),
            ...List.generate(controller.tabs.length, (index) {
              return ListTile(
                leading: controller.tabs[index].icon,
                title: Text(controller.tabs[index].label ?? 'Tab $index'),
                onTap: () {
                  controller.navigateToTab(index);
                  Navigator.pop(context);
                },
              );
            }),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }
}